package com.bluesky.ds;

import java.util.function.Supplier;

public class ReadWriteRoutingStrategyHolder {

    private static ThreadLocal<ReadWriteRoutingStrategy> readWriteRoutingStrategyThreadLocal = new ThreadLocal<>();

    public static void setReadWriteRoutingStrategy(ReadWriteRoutingStrategy strategy) {
        readWriteRoutingStrategyThreadLocal.set(strategy);
    }

    /**
     * 路由到主库
     */
    public static void  master(){
        setReadWriteRoutingStrategy(ReadWriteRoutingStrategy.MASTER);
    }

    /**
     * 路由到从库
     */
    public static void  slave(){
        setReadWriteRoutingStrategy(ReadWriteRoutingStrategy.SLAVE);
    }

    /**
     * 强制走主库执行 execute的代码
     * @param executor
     * @param <T>
     * @return
     */
    public static <T> T hitMaster(Supplier<T> executor){
        ReadWriteRoutingStrategy old = getReadWriteRoutingStrategy();
        try {
            setReadWriteRoutingStrategy(ReadWriteRoutingStrategy.HIT_MASTER);
            return executor.get();
        }finally {
            setReadWriteRoutingStrategy(old);
        }
    }

    public static void clear(){
        readWriteRoutingStrategyThreadLocal.remove();
    }

    /**
     * 获取读写策略
     * @return
     */
    public static ReadWriteRoutingStrategy getReadWriteRoutingStrategy(){
        return readWriteRoutingStrategyThreadLocal.get();
    }
}
